<!doctype html>
<html lang="zh-cmn-Hans">
<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">    
    <title>WebSocket Demo</title>

    <style>
      .myheader {
          background: url(header.png);
          background-size: myheader;
          background-repeat: round;
      }
  </style>
</head>

<body>

发送文本: <input type="text" id="fieldSend" style="width:60%" value="Hello World!"><br>
接收文本: <input type="text" id="fieldRecv" style="width:60%"><br>
日志文本: <input type="text" id="fieldLog" style="width:60%">
<br><br>
<button onclick="openClock()">开启定时器</button>
<button onclick="closeClock()">关闭定时器</button>

</body>

<script>

let openWebSocket = false;
let connection;
let intervalId;

function openClock() {
	intervalId = self.setInterval(clock, 1000);
}

function closeClock() {
	clearInterval(intervalId);
}

function getDateTime() {
	var date = new Date();
	var month = date.getMonth() + 1;
	var day = date.getDate();
	var monthStr = month < 10 ? '0' + month : month;
	var dayStr = day < 10 ? '0' + day : day;
	return date.getFullYear() + '-' + monthStr +	'-' +
		dayStr + ' ' + (date.getHours() + 1) + ':' +
		date.getMinutes() + ':' + date.getSeconds() + ' ' +
		date.getMilliseconds();
}

function getDateTimeFormat() {
	return '[' + getDateTime() + '] ';
}

function addLog(log) {
	document.getElementById("fieldLog").value = getDateTimeFormat() + log;
}

function showMessage(message) {
	document.getElementById("fieldRecv").value = message;
}

function connectServer() {
	if (openWebSocket) {
		//return;
	}
	
	// dotnet-watch browser reload script
	try {
		connection = new WebSocket('ws://127.0.0.1:4040');
	} catch (ex) {
		console.debug(ex);
		addLog(ex);
		return;
	}
	
	connection.onmessage = function (message) {
		if (message.data === 'Reload') {
			console.debug('Server is ready. Reloading...');
			location.reload();
		} else if (message.data === 'Wait') {
			console.debug('File changes detected. Waiting for application to rebuild.');
			const t = document.title; const r = ['☱', '☲', '☴']; let i = 0;
			setInterval(function () { document.title = r[i++ % r.length] + ' ' + t; }, 240);
		} else {
			showMessage(getDateTimeFormat() + message.data);
		}
	}
	connection.onerror = function (event) {
		addLog(event);
		console.debug('dotnet-watch reload socket error.', event);
	}
	connection.onclose = function () { 
		addLog('dotnet-watch reload socket closed.');
		console.debug('dotnet-watch reload socket closed.');
	}
	connection.onopen = function () {
		openWebSocket = true;
		addLog('dotnet-watch reload socket connected.');
		console.debug('dotnet-watch reload socket connected.');
		connection.send(document.getElementById("fieldSend").value);
	}
}

function clock() {
	if (openWebSocket) {
		connection.send(document.getElementById("fieldSend").value);
	} else {
		connectServer();
	}
}

// setInterval(clock, 1000);
</script>

</html>